//
//  STSuitcasePictureViewController.swift
//  SeaTransportManage
//
//  Created by guopengwen on 2021/11/30.
//

import UIKit

class STSuitcasePictureViewController: GPImagePickerController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, STEnchaseTakePictureDelegate {
    
    var orderId: Int = 0
    var selectIndex: Int = -1
    var datasource: Array<Dictionary<String, Any>> = [[ "defaultName": "empty_box_default_1", "status": 0 ], [ "defaultName": "empty_box_default_2", "status": 0 ], [ "defaultName": "empty_box_default_3", "status": 0 ], [ "defaultName": "empty_box_default_4", "status": 0 ], [ "defaultName": "empty_box_default_5", "status": 0 ], [ "defaultName": "empty_box_default_6", "status": 0 ], [ "defaultName": "empty_box_default_7", "status": 0 ], [ "defaultName": "empty_box_default_8", "status": 0 ]]
    let requestApi = GPRequestApi.init()

    override func viewDidLoad() {
        super.viewDidLoad()
        setNavBarTitle("上传提空箱照片")
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.left.equalTo(16)
            make.right.equalTo(-14)
            make.bottom.equalTo(-84)
        }
        
        view.addSubview(submitBtn)
        submitBtn.snp.makeConstraints { (make) in
            make.top.equalTo(collectionView.snp.bottom).offset(10)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(40)
        }
        
        STEnchasePictureCollectionViewCell.registerTo(collectionView)
        submitBtn.addTarget(self, action: #selector(handleSubmitAction), for: .touchUpInside)
    }
    
    @objc func handleSubmitAction () {
        var files: Array<Dictionary<String, Any>> = []
        for item in datasource {
            if(item["fileId"] != nil) {
                files.append(["fileId": item["fileId"]!, "num": files.count + 1] as Dictionary<String, Any> )
            }
        }
        if(files.count < datasource.count) {
            toastInfo("请上传所有图片之后再提交")
        } else {
            self.showLoading("正在加载中...")
            let param = [ "orderId": orderId, "step": 1, "files": files ] as [String : Any]
            requestApi.submitOrder(param) { (isSuccess, response, error) in
                self.hideLoading()
                if(isSuccess) {
                    self.toastInfo("上传成功")
                    let vc: STOrderActionSuccessViewController = STOrderActionSuccessViewController.init()
                    vc.status = 3
                    vc.orderType = "0"
                    self.navigationController?.pushViewController(vc, animated: true)
                } else {
                    self.toastError(error!.1)
                }
            }
        }
    }

    // UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datasource.count
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let h = 200 * (kScreenWidth - 39) / 336
        return CGSize.init(width: (kScreenWidth - 40) / 2.0, height: h)
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = STEnchasePictureCollectionViewCell.reusableCell(collectionView, indexPath: indexPath)
        let item = datasource[indexPath.item]
        cell?.delegate = self
        cell?.update(item, indexPath.item)
        return cell ?? collectionView.dequeueReusableCell(withReuseIdentifier: STEnchasePictureCollectionViewCell.identifier, for: indexPath)
    }
    
    // STEnchaseTakePictureDelegate
    func handleEnchaseTakePhotoAction(_ index: Int) ->Void {
        selectIndex = index
        showPickPictrueSheet()
    }
    
    override func handleImagePickerResult (_ image: UIImage, _ filePath: String) {
        datasource[selectIndex]["image"] = image
        datasource[selectIndex]["status"] = 1
        collectionView.reloadData()
        requestApi.uploadrSinglePic(image) { (isSuccess, response, error) in
            if(isSuccess) {
                let responseData = response as! Dictionary<String, Any>
                let data = responseData["data"] as! Dictionary<String, String>
                self.datasource[self.selectIndex]["status"] = 2
                self.datasource[self.selectIndex]["fileId"] = data["fileId"]
                self.datasource[self.selectIndex]["filePath"] = data["filePath"]
                self.collectionView.reloadData()
            }
        }
    }
   
    lazy var collectionView: UICollectionView = {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
        layout.minimumLineSpacing = 9
        layout.minimumInteritemSpacing = 8
        let collectView: UICollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        collectView.delegate = self
        collectView.dataSource = self
        collectView.backgroundColor = UIColor.init(hexString: "#F7F7F7", alpha: 1)
        return collectView
    }()

    lazy var submitBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.backgroundColor = COLOR_HEX(hexString: "#008CFF", alpha: 1)
        btn.setTitle("确认上传", for: .normal)
        btn.layer.cornerRadius = 20
        btn.setTitleColor(UIColor.white, for: UIControl.State.normal)
        return btn
    }()
}
